package com.rectcircle.scalatrateset.config

import com.mchange.v2.c3p0.ComboPooledDataSource
import org.slf4j.LoggerFactory
import org.squeryl.Session
import org.squeryl.adapters.MySQLAdapter

trait DbConfig {
	
	val logger = LoggerFactory.getLogger(getClass)
	
	var cpds = new ComboPooledDataSource

	
	//配置连接数据库信息
	val url = "jdbc:mysql://localhost:3306/library"
	val driver = "com.mysql.jdbc.Driver"
	val username = "root"
	val password = "123456"
	
	def initDbConnection = {
		cpds.setDriverClass(driver)
		cpds.setJdbcUrl(url)
		cpds.setUser(username)
		cpds.setPassword(password)
		
		cpds.setMinPoolSize(1)
		cpds.setAcquireIncrement(1)
		cpds.setMaxPoolSize(50)
		
		import org.squeryl.SessionFactory
		Class.forName(driver)
		if (SessionFactory.concreteFactory.isEmpty) {
			SessionFactory.concreteFactory = Some(() =>
				Session.create(cpds.getConnection, new MySQLAdapter))
		}
		
	}
	
	def closeDbConnection() {
		logger.info("Closing c3po connection pool")
		cpds.close()
	}
}